#include "List.h"
#include <stdlib.h>

List::List() : Header(0,0)
{
ListCount = 0;
}

List::~List(void)
{

}

void List::addListItem(ListItem &newItem)
{
ListItem *p = getLastItem();
ListItem *newp = new ListItem(newItem);

if (p==NULL)
	Header.setNext(newp);
else
	p->setNext(newp);

ListCount++;

}
ListItem * List::getFirstItem()
{
	return Header.getNext();
}
ListItem * List::getLastItem()
{
ListItem *p = getFirstItem();
	
	if (p!=NULL)
		while (p->getNext() != NULL)
				p = p->getNext();
	
return p;
}

ListItem * List::getItemByIndex(int i)
{
ListItem *p = getFirstItem();
while (i--)
	p = p->getNext();
return p;
}

void List::PrintList  (ListItem *From)
{
	if (From !=NULL)
	{
		cout<<From<<endl;
		PrintList(From->getNext());
	}
	else
	{
	cout<<"-----"<<endl;
	}
}

void List::deleteListItem(ListItem *delItem)
{
	ListItem *p = getPrevItem(delItem);
	if (p==NULL)
		Header.setNext(delItem->getNext());
	else
		p->setNext(delItem->getNext());
	
	delete delItem;
	ListCount--;

}

ListItem * List::getPrevItem(ListItem *item)
{
	return (*this)[(*this)[*item] - 1];
}
ListItem *List::operator[](int ind)
{
	if (ind>=0)
		return getItemByIndex(ind);
	else if (ind==-1)
		return &Header;
	else
		return NULL;
}
int List::operator[](const ListItem &item)
{
	if (isEmpty())
		return -999;
	else
	{
		ListItem *p = getFirstItem();
		bool found = false;
		int cnt = -1;
		while ((p!=NULL) && (!found))
			{
				if (*p==item)
					found = true;
				p = p->getNext();
				cnt++;
			}
		if (found)
			return cnt;
		else
			return -1;

	}
}
bool List::isEmpty()
{
	return Header.getNext()==NULL;
}

void List::addListItemBefore( ListItem &newItem,ListItem *Before)
{
ListItem *p = new ListItem(newItem);
ListItem *prev = getPrevItem(Before);
p->setNext(Before);
prev->setNext(p);
ListCount++;
}